<?php
/**
* @version $Id: controller.php 18 2009-12-07 11:22:56Z truongnhan0311 $
* @author truongnhan0311
* @package	wrd component
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport('joomla.application.component.controller');

class WrdController extends JControllerLegacy {
	
	function display($cache = false) {

		if (!JRequest::getVar('view'))
			JRequest::setVar('view', 'profile');

		parent::display($cache);
	}
	
	function JSONPOSXMSDiscountPolicy(){
		WrdHelper::JSONPOSXMSIpConnect();
		
		$post = JRequest::getVar('parameter');
		$arr = json_decode($post);
		
		if($arr->token != '')
		{
			$arr_member = WrdHelper::JSONPOSXMSIsValidMemberID($arr->MemberID);
			
			$member_long = $arr_member[long];
			$member_id = $arr_member[short];
			//print_r($arr_member);
			
			$outlet_code = $arr->OutletCode;
		
			if($member_id == false){
				$return['discount'] 			= '0%';
				$return['MemberID'] 			= $arr->MemberID;
				$return['OutletCode'] 			= $outlet_code;
				$return['message'] 				= 'Non Member';
				$return['pointbalance'] 		= '';
				
				$return = json_encode($return);
				file_put_contents('logs-wrd'.DS.'discountpolicy'.DS.'failure'.DS.date("Y-m-d").'-discount-policy-failure.txt', $return."\t".date("H:i:s")."\n", FILE_APPEND);
				echo $return;
				exit();
			}
			
			//get list 
			$list_rules = WrdHelper::getPublishRule();
			$profile = WrdHelper::getProfileDiscountPolicy($member_id);
			$full_profile = WrdHelper::getUserProfile($member_id,'member_id');
			
			if($profile->member_id == ''){
				$return['discount'] 			= '0%';
				$return['MemberID'] 			= $member_long;
				$return['OutletCode'] 			= $outlet_code;
				$return['message'] 				= 'Non Member';
				$return['pointbalance'] 		= '';
				$return['lastvisitplace']		= '';
			
				$return = json_encode($return);
				file_put_contents('logs-wrd'.DS.'discountpolicy'.DS.'failure'.DS.date("Y-m-d").'-discount-policy-failure.txt', $return."\t".date("H:i:s")."\n", FILE_APPEND);
				echo $return;
				exit();
			}
			
			
			if(count($list_rules) != 0){
				//prepair list
				$list_rules = WrdHelper::orderList($list_rules);
				$match_rule = $list_rules[$outlet_code];
				
				//print_r($match_rule);
				
				if(count($match_rule) > 0){

					$transaction = WrdHelper::getTransactionDiscountPolicy($outlet_code);
					$discount = false;
					foreach ($match_rule as $rule_priority){
						foreach ($rule_priority as $rule_id){
							$discount = WrdHelper::checkRuleMatch($rule_id,$profile,$transaction,$outlet_code,1);
							if(is_array($discount))
								break;
						}
						
						if(is_array($discount))
							break;
					}
					
					
					if(is_array($discount)){
						$return['discount'] = $discount['discount'];
						$ispercent = substr(trim($discount['discount']), -1);
						
						if($ispercent == '%')
							$msg = $discount['msg'].' ('.$discount['discount'].' off)';
						else 
							$msg = $discount['msg'].' ('.$discount['discount'].' VND off)';
					}
					else{
						$return['discount'] = '10%';
						$msg = $discount['msg'].' ('.$return['discount'].' off)';
					}

					$return['MemberID'] 			= $member_long;
					$return['OutletCode'] 			= $outlet_code;
					$return['f_name'] 				= $profile->f_name;
					$return['l_name'] 				= $profile->l_name;
					$return['pointbalance'] 		= $full_profile->p_o_u;
					
					$outlet = WrdHelper::getOutlet($full_profile->outlet_code);
					
					$return['lastvisitplace'] = $outlet->name;
					
					if ($discount['msg'] == '' && $return['discount'] == '10%') $return['message'] = 'VIP Discount'.$msg;
					else $return['message'] = $msg;
					
					$return = json_encode($return);
					file_put_contents('logs-wrd'.DS.'discountpolicy'.DS.'success'.DS.date("Y-m-d").'-discount-policy-success.txt', $return."\t".date("H:i:s")."\n", FILE_APPEND);

				}else{
					$return['discount'] 			= '10%';
					$return['MemberID'] 			= $member_long;
					$return['OutletCode'] 			= $outlet_code;
					$return['f_name'] 				= $profile->f_name;
					$return['l_name'] 				= $profile->l_name;
					$return['message'] 				= 'VIP Discount (10% off)';
					$return['pointbalance'] 		= $full_profile->p_o_u;
					
					$outlet = WrdHelper::getOutlet($full_profile->outlet_code);
					
					$return['lastvisitplace']		= $outlet->name;
					
					$return = json_encode($return);

					file_put_contents('logs-wrd'.DS.'discountpolicy'.DS.'success'.DS.date("Y-m-d").'-discount-policy-success.txt', $return."\t".date("H:i:s")."\n", FILE_APPEND);
				}
			} else {
				//return because no rule match 10%
				$return['discount'] 			= '10%';
				$return['MemberID'] 			= $member_long;
				$return['OutletCode'] 			= $outlet_code;
				$return['f_name'] 				= $profile->f_name;
				$return['l_name'] 				= $profile->l_name;
				$return['message'] 				= 'VIP Discount (10% off)';
				$return['pointbalance'] 		= $full_profile->p_o_u;
				
				$outlet = WrdHelper::getOutlet($full_profile->outlet_code);
				
				$return['lastvisitplace']		= $outlet->name;
				
				$return = json_encode($return);

				file_put_contents('logs-wrd'.DS.'discountpolicy'.DS.'success'.DS.date("Y-m-d").'-discount-policy-success.txt', $return."\t".$discount['rule']."\t".date("H:i:s")."\n", FILE_APPEND);
			}
		}
		else{
			$return['message'] = 'Missing Token';
		}

		echo $return;
		exit();
	}
	
	function JSONPOSXMSDiscountPolicyInvoice(){
		
		WrdHelper::JSONPOSXMSIpConnect();
		
		$post = JRequest::getVar('parameter');
		$arr = json_decode($post);
		
		if($arr->token != '')
		{
			$arr_member = WrdHelper::JSONPOSXMSIsValidMemberID($arr->MemberID);
			
			$member_long = $arr_member[long];
			$member_id = $arr_member[short];
			
			$outlet_code = $arr->OutletCode;
		
			if($member_id == false){
				$return['discount'] 			= '0%';
				$return['MemberID'] 			= $arr->MemberID;
				$return['OutletCode'] 			= $outlet_code;
				$return['message'] 				= 'Non Member';
				$return['pointbalance'] 		= '';
				
				$return = json_encode($return);
				file_put_contents('logs-wrd'.DS.'discountpolicy'.DS.'failure'.DS.date("Y-m-d").'-discount-policy-failure.txt', $return."\t".date("H:i:s")."\n", FILE_APPEND);
				echo $return;
				exit();
			}
			
			//get list 
			$list_rules = WrdHelper::getPublishRule();
			$profile = WrdHelper::getProfileDiscountPolicy($member_id);
			$full_profile = WrdHelper::getUserProfile($member_id,'member_id');
			
			if($profile->member_id == ''){
				$return['discount'] 			= '0%';
				$return['MemberID'] 			= $member_long;
				$return['OutletCode'] 			= $outlet_code;
				$return['message'] 				= 'Non Member';
				$return['pointbalance'] 		= '';
				$return['lastvisitplace']		= '';
			
				$return = json_encode($return);
				file_put_contents('logs-wrd'.DS.'discountpolicy'.DS.'failure'.DS.date("Y-m-d").'-discount-policy-failure.txt', $return."\t".date("H:i:s")."\n", FILE_APPEND);
				echo $return;
				exit();
			}
			
			
			if(count($list_rules) != 0){
				//prepair list
				$list_rules = WrdHelper::orderList($list_rules);
				$match_rule = $list_rules[$outlet_code];
				
				//print_r($match_rule);
				
				if(count($match_rule) > 0){

					$transaction = WrdHelper::getTransactionDiscountPolicy($outlet_code);
					$discount = false;
					foreach ($match_rule as $rule_priority){
						foreach ($rule_priority as $rule_id){
							$discount = WrdHelper::checkRuleMatch($rule_id,$profile,$transaction,$outlet_code,0);
							if(is_array($discount))
								break;
						}
						
						if(is_array($discount))
							break;
					}
					
					
					if(is_array($discount)){
						$return['discount'] = $discount['discount'];
						$ispercent = substr(trim($discount['discount']), -1);
						
						if($ispercent == '%')
							$msg = $discount['msg'].' ('.$discount['discount'].' off)';
						else 
							$msg = $discount['msg'].' ('.$discount['discount'].' VND off)';
					}
					else{
						$return['discount'] = '10%';
						$msg = $discount['msg'].' ('.$return['discount'].' off)';
					}

					$return['MemberID'] 			= $member_long;
					$return['OutletCode'] 			= $outlet_code;
					$return['f_name'] 				= $profile->f_name;
					$return['l_name'] 				= $profile->l_name;
					$return['pointbalance'] 		= $full_profile->p_o_u;
					
					$outlet = WrdHelper::getOutlet($full_profile->outlet_code);
					
					$return['lastvisitplace']		= $outlet->name;
					
					if ($discount['msg'] == '' && $return['discount'] == '10%') $return['message'] = 'VIP Discount'.$msg;
					else $return['message'] = $msg;
					
					$return = json_encode($return);
					file_put_contents('logs-wrd'.DS.'discountpolicy'.DS.'success'.DS.date("Y-m-d").'-discount-policy-success.txt', $return."\t".date("H:i:s")."\n", FILE_APPEND);

				}else{
					$return['discount'] 			= '10%';
					$return['MemberID'] 			= $member_long;
					$return['OutletCode'] 			= $outlet_code;
					$return['f_name'] 				= $profile->f_name;
					$return['l_name'] 				= $profile->l_name;
					$return['message'] 				= 'VIP Discount';
					$return['pointbalance'] 		= $full_profile->p_o_u;
					$outlet = WrdHelper::getOutlet($full_profile->outlet_code);
					$return['lastvisitplace']		= $outlet->name;
					
					$return = json_encode($return);

					file_put_contents('logs-wrd'.DS.'discountpolicy'.DS.'success'.DS.date("Y-m-d").'-discount-policy-success.txt', $return."\t".date("H:i:s")."\n", FILE_APPEND);
				}
			} else {
				//return because no rule math 10%
				$return['discount'] 			= '10%';
				$return['MemberID'] 			= $member_long;
				$return['OutletCode'] 			= $outlet_code;
				$return['f_name'] 				= $profile->f_name;
				$return['l_name'] 				= $profile->l_name;
				$return['message'] 				= 'VIP Discount';
				$return['pointbalance'] 		= $full_profile->p_o_u;
				$outlet = WrdHelper::getOutlet($full_profile->outlet_code);
				$return['lastvisitplace']		= $outlet->name;
				
				$return = json_encode($return);
				
				
				file_put_contents('logs-wrd'.DS.'discountpolicy'.DS.'success'.DS.date("Y-m-d").'-discount-policy-success.txt', $return."\t".$discount['rule']."\t".date("H:i:s")."\n", FILE_APPEND);
			}
		}
		else{
			$return['message'] = 'Missing Token';
		}

		echo $return;
		exit();
	}
	
	function JSONPOSXMSTransaction(){
		WrdHelper::JSONPOSXMSIpConnect();
		require_once( JPATH_SITE.DS.'utilities'.DS.'pointProvider.php' );
		
		$post = JRequest::getVar('parameter');
		$arr = json_decode($post);
		WrdHelper::sendEmailToAdminForDebuging($post);
		
		if($arr->token != '')
		{
			$db = JFactory::getDbo();
			$obj = new stdClass();
		
			$json_logged_transaction = @file_get_contents('logs-wrd'.DS.'transactions'.DS.date("Y-m-d").'-transaction-received.txt');
			$logged_transaction = json_decode($json_logged_transaction);

			$tmp = explode('/',$arr->BusinessDate);
			$tmpend = explode('/',$arr->EndDate);
			
			$endtime  = $tmp[2].'-'.$tmp[1].'-'.$tmp[0];
			$date_receipt = $tmpend[2].'-'.$tmpend[0].'-'.$tmpend[1].' '.$arr->EndTime;
			
			$discount_check = $date_receipt;
			$discount_check = date('Y-m-d',strtotime($discount_check));
			
			unset($tmp);
			$tmp = explode(' ',$arr->BeginTime);
			$new_tmp = explode(':',$tmp[0]);
		
			if($tmp[1] == 'PM')
				if(intval($new_tmp[0]) < 12)
				$new_tmp[0] = intval($new_tmp[0]) + 12;
		
			$date_receipt = $date_receipt .' '.$new_tmp[0].':'.$new_tmp[1].':'.$new_tmp[2];
			
			$vowels = array(",", ".00");
			$obj->id = null;
		
			$arr_member = WrdHelper::JSONPOSXMSIsValidMemberID($arr->MemberID);
			if($arr_member === false){
				file_put_contents('logs-wrd'.DS.'transactions'.DS.'error'.DS.date("Y-m-d").'-transaction-received_profile.txt', $post."\t".date("H:i:s")."\n", FILE_APPEND);
				$return['message'] = 'Error';
				$return['note'] = 'Missing Profile';
				echo json_encode($return);
				exit();
			}
			
			$member_id = $arr_member['short'];
			
			$obj->vip_number = $member_id;
			$obj->transaction_id = $arr->CheckNo;
			$obj->date_receipt = $date_receipt;
			$obj->endtime = $endtime;
			$obj->outlet = $arr->StoreCode.$arr->OutletCode;
			
			if(count($logged_transaction) > 0){
				if(in_array($obj->outlet.'|'.$obj->transaction_id, $logged_transaction)){
					$return['message'] = 'Error';
					$return['note'] = 'Double Transaction';
					echo json_encode($return);
					exit();
				}
			}
			$logged_transaction[] = $obj->outlet.'|'.$obj->transaction_id;
			
			$profile = WrdHelper::getUserProfile($obj->vip_number,'member_id');
			if($profile->member_id == ''){
				file_put_contents('logs-wrd'.DS.'transactions'.DS.'error'.DS.date("Y-m-d").'-transaction-received_profile.txt', $post."\t".date("H:i:s")."\n", FILE_APPEND);
				$return['message'] = 'Error';
				$return['note'] = 'Missing Profile';
				echo json_encode($return);
				exit();
			}
				
			if($profile->outlet_date == NULL || $profile->outlet_date == '' || $profile->outlet_date == '0000-00-00 00:00:00'){
					
				$q = 'UPDATE `#__wrd_profile` SET `outlet_code` = "'.$obj->outlet.'",`outlet_date` = "'.$obj->date_receipt.'" WHERE `#__wrd_profile`.`member_id` ="'.$obj->vip_number.'"';
				$db->setQuery($q);
				$db->query();
			}
			else if(($outlet_date->outlet_date < $obj->date_receipt)){
				$q = 'UPDATE `#__wrd_profile` SET `outlet_code` = "'.$obj->outlet.'",`outlet_date` = "'.$obj->date_receipt.'" WHERE `#__wrd_profile`.`member_id` ="'.$obj->vip_number.'"';
				$db->setQuery($q);
				$db->query();
			}
		
			$obj->pax = $arr->Cover;
			$obj->food = intval(str_ireplace($vowels, '', $arr->Food));
			$obj->beverage = intval(str_ireplace($vowels, '', $arr->Beverage));
			$obj->liquor = intval(str_ireplace($vowels, '', $arr->Liquor));
			$obj->other = intval(str_ireplace($vowels, '', $arr->Other));
			$obj->discount = intval(str_ireplace($vowels, '', $arr->Discount));
			$obj->sc = intval(str_ireplace($vowels, '', $arr->ServiceCharge));
			$obj->vat = intval(str_ireplace($vowels, '', $arr->Tax));
			$obj->total = intval(str_ireplace($vowels, '', $arr->ActualPaid));
			$obj->netsale = intval(str_ireplace($vowels, '', $arr->NetSale));
			#$obj->netsale = intval($obj->total - $obj->vat - $obj->sc );
			$obj->created_date = date("Y-m-d H:i:s");
			$obj->created_id = 1;
			$obj->pay_type = null;
			$obj->file_id = null;
			$obj->convert = 1;
			$db->insertObject('#__wrd_transaction', $obj);
			$insert_id = $db->insertid();
			//rule 3
			$query = 'SELECT * FROM #__wrd_discount_transaction WHERE outlet_id = '.$obj->outlet;
			$discount_rs = $db->setQuery($query)->loadObject();
			
			if($discount_rs->outlet_id == ''){
				//new
				$discountobj = new stdClass();
				$discountobj->outlet_id = $obj->outlet;
				$discountobj->date = date("Y-m-d");
				$discountobj->total = 1;
				$discountobj->used = 0;

				$db->insertObject('#__wrd_discount_transaction', $discountobj);
			}
			else{
				$discountobj = new stdClass();
				$discountobj->outlet_id = $obj->outlet;
				

				$current_date = date("Y-m-d");
				if($current_date == $discount_rs->date)
				{
					$discountobj->date = $discount_rs->date;
					$discountobj->total = intval($discount_rs->total + 1);
					$discountobj->used = $discount_rs->used;
					
				}else{
					$discountobj->date = $current_date;
					$discountobj->used = 0;
					$discountobj->total = 1;
				}
				
				$db->updateObject('#__wrd_discount_transaction', $discountobj,'outlet_id');
			}
			
			//rule 2
			// $query = 'UPDATE #__wrd_discount_profile SET first_use = 1 WHERE member_id = '.$member_id;
			// $db->setQuery($query)->query();

			//rule 4
			// $query = 'SELECT * FROM #__wrd_discount_profile WHERE member_id = '.$member_id;
			// $discount_profile = $db->setQuery($query)->loadObject();
			// 			
			// 			
			// $floor_point_log = $discount_profile->floor_point_log;
			// 			
			// if($floor_point_log != '')
				// $floor_point_log = unserialize($floor_point_log);
			// 
			// if($floor_point_log[outlet] == $obj->outlet &&  $floor_point_log[time_log] == $discount_check)
			// {
				// $discount_profile->floor_point_log = '';
				// $discount_profile->floor_point = $floor_point_log[floor_point];
				// $db->updateObject('#__wrd_discount_profile',$discount_profile,'member_id');
			// }else{
				// $discount_profile->floor_point_log = '';
				// $db->updateObject('#__wrd_discount_profile',$discount_profile,'member_id');
			// }
			// 			
			//rule 5
			// $available_lucky_log = $discount_profile->available_lucky_log;
			// if($available_lucky_log != '')
				// $available_lucky_log = unserialize($available_lucky_log);
			// 				
			// if($available_lucky_log[outlet] == $obj->outlet &&  $available_lucky_log[time_log] == $discount_check)
			// {
				// $discount_profile->available_lucky_log = '';
				// $discount_profile->available_lucky = $available_lucky_log[available_lucky];
				// $db->updateObject('#__wrd_discount_profile',$discount_profile,'member_id');
			// }else{
				// $discount_profile->available_lucky_log = '';
				// $db->updateObject('#__wrd_discount_profile',$discount_profile,'member_id');
			// }

			$month = date('m',strtotime($date_receipt));
			$year = date('Y',strtotime($date_receipt));
			if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
				while(($month != date('m'))||($year != date('Y'))){
					WrdHelper::uSummarySpend($obj->vip_number,$year,$month);
					if($month+1 <=12) ++$month;
					else {$month = 1;++$year;}
				}
			}
		
			WrdHelper::uSummarySpend($obj->vip_number,date('Y'),date('m'));
		
			//Update wrd_disscount_profile
			WrdHelper::updatePointOfUser($profile->user_id,$profile->member_id,$profile->dob,$profile->f_name,$profile->l_name);
		
			$totalSpend = WrdHelper::getTotalTransaction($obj->vip_number);
			$sql = 'UPDATE #__wrd_profile SET total_spend = '.$totalSpend->total .' WHERE member_id = '.$obj->vip_number;
			$db->setQuery($sql);
			$db->query();
		
				
			//convert point
			$moneyForOnePoint = PointProvider::getConfigByName($db, 'money_for_one_point');
			$moneyForOnePoint = ($moneyForOnePoint > 0 ? $moneyForOnePoint : 50000);
		
			$defaultPointPerMoney  = PointProvider::getConfigByName($db, 'default_point_per_money');
			$defaultPointPerMoney = ($defaultPointPerMoney > 0 ? $defaultPointPerMoney : 100);
		
			$item = $obj;
			$item->id = $insert_id;
			//Call function machPoint in components/com_wrd/helpers/wrd.php.Note by Hung
			$point = WrdHelper::machPoint($item->id,'transaction');
			
				
			if($point->point == 0){
				$point->point = $defaultPointPerMoney;
			}
				
			if(($point->f==0)&&($point->b==0)&&($point->o==1))
				$p = intval(($item->other) / $moneyForOnePoint) * $point->point;
				
			else if(($point->f==0)&&($point->b==1)&&($point->o==0))
				$p = intval(($item->beverage) / $moneyForOnePoint) * $point->point;
				
			else if(($point->f==0)&&($point->b==1)&&($point->o==1))
				$p = intval(($item->beverage+$item->other) / $moneyForOnePoint) * $point->point;
				
			else if(($point->f==1)&&($point->b==0)&&($point->o==0))
				$p = intval($item->food / $moneyForOnePoint) * $point->point;
				
			else if(($point->f==1)&&($point->b==0)&&($point->o==1))
				$p = intval(($item->food+$item->other) / $moneyForOnePoint) * $point->point;
				
			else if(($point->f==1)&&($point->b==1)&&($point->o==0))
				$p = intval(($item->food+$item->beverage) / $moneyForOnePoint) * $point->point;
				
			else
				$p = intval(($item->netsale) / $moneyForOnePoint) * $point->point;
				
			$expire  = WrdHelper::calculateExpiredDate($item->date_receipt);
		
			if($expire != '0000-00-00'){
				if(strtotime($expire.' 23:59:59') < time())
					$expired = 1;
				else $expired = 0;
			}
			else
				$expired = 0;

			//insert point table
			$obj = new stdClass;
			$obj->id = null;
			$obj->user_id = $point->user_id;
			$obj->transaction = $point->tran;
			$obj->type = '0';
			$obj->outlet = $item->outlet;
			$obj->point = $p;
			$obj->expire = $expire;
			$obj->expired = $expired;
			$obj->remain = $p;
			$obj->des = 'transaction';
			$obj->created_id = 1 ;
			$obj->created_date = $item->date_receipt;
			$obj->modify_id = '' ;
			$obj->modify_date = '' ;
			$db->insertObject('#__wrd_point', $obj);
				
				
			// Update lai point summary cho user
			$month = date('m',strtotime($obj->created_date));
			$year = date('Y',strtotime($obj->created_date));
		
			if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
					
				while(($month != date('m'))||($year != date('Y'))){
					WrdHelper::updateSummaryPoint($obj->user_id,$year,$month);
					if($month+1 <=12) ++$month;
					else {$month = 1;++$year;}
				}
			}
			WrdHelper::updateSummaryPoint($obj->user_id,date('Y'),date('m'));
		
			$p_o_u = WrdHelper::getPoints($obj->user_id);
			$sql = 'UPDATE #__wrd_profile SET p_o_u = '.$p_o_u->point.',point_life_time = '.$p_o_u->point_life_time.' WHERE user_id = '.$obj->user_id;
			$db->setQuery($sql);
			$db->query();
		
			WrdHelper::updatePointOfUser($obj->user_id,$profile->member_id,$profile->dob,$profile->f_name,$profile->l_name);
		
			$query = 'UPDATE #__wrd_transaction SET `convert` = 1 WHERE transaction_id ='.$point->tran;
		
			$db->setQuery($query);
			$db->query();

			file_put_contents('logs-wrd'.DS.'transactions'.DS.'received'.DS.date("Y-m-d").'-transaction-received.txt', $post."\t".date("H:i:s")."\n", FILE_APPEND);
			file_put_contents('logs-wrd'.DS.'transactions'.DS.date("Y-m-d").'-transaction-received.txt', json_encode($logged_transaction)."\n");
			
			$return['message'] = 'Success';
		}
		else{
			$return['message'] = 'Missing Token';
		}
		
		echo json_encode($return);
		exit();
	}
	
	function receiveJSON(){
	
		// Check IP Address for Security issue
		$arr_allow_ip = array();
		$arr_allow_ip[] = '10.200';

		$server_ip = explode('.',$_SERVER['SERVER_ADDR']);
		
		
		$str_server_ip = $server_ip[0].'.'.$server_ip[1];

		if(!in_array($str_server_ip,$arr_allow_ip)){
			echo 'Security Issue';
			exit();
		}
		// Get name and value data
		$post = JRequest::getVar('parameter');  
		//$post = urldecode($post);
		$arr = json_decode($post);
		// In this example, we write all parameter into file
		file_put_contents('json_receive_'.time(), print_r($arr,1));

		// For member id, you can get and insert that info into database 

		// Return message to client 
		$return = array();                                                             
		if($arr->token != '')
		{
			$return['message'] = 'Success';
			$return['time'] = time();
		}
		else{
			$return['message'] = 'Error';
			$return['time'] = time();
		}

		echo json_encode($return);
		exit();
	}

	//test send Json
	function sendJSON(){
		$app = &JFactory::getApplication('site');
		// Create token
		$post['token'] = time();

		// Set type of JSON (Have 3 values)
		// Type: transaction || Type: member_profile || Type: discount
		$post['type'] = "member";

		// Please replace value by data from POSXMS/DOTPos DB
		$post['discount'] = '10%';
		$post['MemberID'] = '880013982201';
		$post['OutletCode'] = '226';

		// Encode $POST into JSON Type
		$json = json_encode($post);

		// URL of JSON Function
		$target_url = 'http://10.200.2.23/wmcvip/?option=com_wrd&task=JSONPOSXMSDiscountPolicy';

		$p = array('parameter' => $json);
		// Set up CURL to send JSON files
		// For more information about CURL: http://en.wikipedia.org/wiki/CURL
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$target_url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 120);
		curl_setopt($ch, CURLOPT_POST,1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $p);

		// Send JSON files
		$result=curl_exec($ch);
		curl_close($ch);
		// Show the result whether we sent JSON file success or not
		print_r($result);

		// Try send JSON file again in case NETWORK failure
		if($result == ''){
			// Print error to log file
			file_put_contents('dotpos_d_', print_r('delay_'.time(),1), FILE_APPEND);
			$app->redirect(JURI::base().'index.php?option=com_wrd&task=receiveJSON');
		}
		// We can do other action after success sent
		// In this example, we print result into file
		file_put_contents('json_send_'.time(), print_r($result,1));
		exit();
	}
	

	function renewMember(){
		$userID = JRequest::getVar('userid');
		if ($userID){
			$member_id = $this->getUserInfo($userID);
			if($member_id){
				$memberIDNew = $this->generateMemberId();
				$this->updateUser($userID, $memberIDNew, $member_id);
			}
		}
		$this->setRedirect(JRoute::_('index.php?option=com_wrd&view=profile&layout=default&id=1&Itemid=112', false));
	}
	
	    //checkpassword
    public function checkpass($pass, $ajax = 0){
    	$db = &JFactory::getDbo();
    	$query = $query = 'SELECT password FROM #__users WHERE password LIKE"%'.$db->Quote(md5($pass)).'%"';
    	$db->setQuery($query);
    	$rs = $db->loadObject();
    	
    	if($ajax == 1){
    		echo $result->password;
    		jexit();
    	}
    }
    
	
	protected function generateMemberId(){
		
		$db = JFactory::getDBO();
		$query_lucky = 'SELECT number FROM #__wrd_lucky_num WHERE `published`=1 and `available`=1';
		$db->setQuery($query_lucky);
		$rs_lucky = $db->loadResultArray();
		//print_r($rs_lucky)	;	
		$query = 'SELECT member_id FROM #__wrd_profile ' ;
		$query.= ' WHERE member_id NOT IN (SELECT number FROM #__wrd_lucky_num WHERE `published`=1 and `available`=1)';		
		$query.= ' ORDER BY member_id DESC LIMIT 1';
		$db->setQuery($query);
		$rs = $db->loadObject();
		$code = $rs->member_id + 1;
		
		$tmparr = $rs_lucky;
		$total = count($tmparr)*2 ;
		for($i = 0 ; $i <= $total ; $i++){
			$tmparr[] = $code + $i ;
		}
		$tmparr = array_unique($tmparr,SORT_NUMERIC) ;
		sort($tmparr) ;
		foreach ($tmparr as $val){
			if(in_array($val, $rs_lucky)){
				continue;
			}else{
				$code = $val;
				break;
			}
		}
		return $code ;
		//jexit();
	}

	protected function getUserInfo($userID=null){
		if(isset($userID) && $userID != ''){
			$db = JFactory::getDbo();
			$query = "SELECT member_id FROM #__wrd_profile WHERE sha1(user_id)='".$userID. "' LIMIT 1";
			$db->setQuery($query);
			$rs = $db->loadObject();
			if($rs->member_id){
				return $rs->member_id;
			}
			return false;
		}
	}
	
	function updateUser($userID=null, $memberIDNew=null, $memberIDOld=null){
		$db = JFactory::getDbo();

		$sqlQuery = sprintf("UPDATE #__wrd_profile SET member_id=$memberIDNew, renew='I' WHERE sha1(user_id)=%s", $db->Quote($userID));
		$updateNewMemberID = $db->setQuery($sqlQuery);
		$updateNewMemberID->query();
		
		$sqlQuery = sprintf("UPDATE #__wrd_transaction SET vip_number=$memberIDNew WHERE vip_number=%s", $db->Quote($memberIDOld));
		$updateNewMemberID = $db->setQuery($sqlQuery);
		$updateNewMemberID->query();
	}
	
	function getCompanies()
	{
		$q = JRequest::getVar('q');
		$model = $this->getModel('companyname');
	
		$tagList = $model->getListCompany($q);
	
		if(is_array($tagList))
		{
			foreach($tagList as $t)
			{
				echo "{$t->name}\n";
			}
		}
	
		jexit();
	}
	
	function eventStatus(){
		$db = &JFactory::getDbo();
		$user = JFactory::getUser();
		if($user->id == 0){
			echo 0;
			jexit();
		}
		$status = JRequest::getVar('event_status');
		$event_title = JRequest::getVar('event_title');
		$event_id = JRequest::getVar('event_id');
		
		$obj = new stdClass();
		$obj->event_name = $event_title;
		$obj->user_id = $user->id;
		$obj->article_id = $event_id;
		$obj->status = $status;
		
		$db->insertObject('#__wrd_event_status', $obj);
		
		echo 1;
		jexit();
	}
}
?>